#include "Avalon/Codecs/CodedWriter.hpp"
#include "Avalon/Codecs/Encoder.hpp"
#include "Avalon/IO/Buffer.hpp"

using namespace Avalon;
using namespace Avalon::Codecs;
using namespace Avalon::IO;
using namespace Avalon::Threading;

CodedWriter::CodedWriter(Carry<Writer> destination, Encoder* encoder,
    bool encodeInPlace)
    : m_destination(destination),
      m_encoder(encoder),
      m_encodeInPlace(encodeInPlace) {}

CodedWriter::~CodedWriter() {}

Async<void>::Ptr CodedWriter::Write(const void* data, int size) {
  if(m_encodeInPlace) {
    m_encoder->EncodeInPlace(const_cast<void*>(data), size);
    return m_destination->Write(data, size);
  } else {
    return m_destination->Write(m_encoder->Encode(data, size));
  }
}

Async<void>::Ptr CodedWriter::Write(const Buffer& data) {
  if(m_encodeInPlace) {
    m_encoder->EncodeInPlace(const_cast<Buffer*>(&data));
    return m_destination->Write(data);
  } else {
    return m_destination->Write(m_encoder->Encode(data));
  }
}
